from rest_framework.response import Response
from rest_framework.views import APIView
from meiduo_mall.utils.qq_sdk import OAuthQQ
from .models import OAuthQQUser
from meiduo_mall.utils import jwt_token
from .serializers import OAuthQQUserSerializer
from rest_framework import generics


class QQAuthUrlView(APIView):
    def get(self, request):
        # 获取客户端的next参数
        state = request.query_params.get('next')
        # 获取授权的url地址
        oauthqq = OAuthQQ(state=state)
        login_url = oauthqq.get_qq_login_url()
        # 响应
        return Response({'login_url': login_url})


# class QQAuthOpenidView(APIView):
class QQAuthOpenidView(generics.CreateAPIView):
    def get(self, request):
        # 接收code
        code = request.query_params.get('code')

        try:
            # 与qq服务器交互
            oauthqq = OAuthQQ()
            # 根据code请求qq服务器获取token
            token = oauthqq.get_access_token(code)
            # 根据token请求qq服务器获取openid
            openid = oauthqq.get_openid(token)
        except:
            return Response({'message': '访问QQ服务器失败'})

        # 判断是否绑定现有账号
        try:
            qq = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未查询，说明第一次授权，返回绑定页面，包含加密的openid
            # 1.加密
            access_token = OAuthQQ.generate_openid_token(openid)
            # 2.响应
            return Response({'access_token': access_token})
        else:
            # 查询到数据，说明已经绑定过，状态保持，返回登录成功
            # 生成状态保持的jwt
            token = jwt_token.get_token(qq.user)

            # 响应
            return Response({
                'user_id': qq.user.id,
                'username': qq.user.username,
                'token': token
            })

    # 指定序列化器，完成验证
    serializer_class = OAuthQQUserSerializer



